package com.shushan.pages;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.huawei.android.hms.agent.HMSAgent;
import com.huawei.android.hms.agent.common.handler.CheckUpdateHandler;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.home.HomeActivity;
import com.shushan.home.TabHomeActivity;
import com.shushan.home.bean.UpdateBean;
import com.shushan.login.LoginOrRegisterActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.DeviceUtil;
import com.shushan.util.DialogUtil;
import com.shushan.util.FileSizeUtil;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.versionupdate.entity.VersionUpdateConfig;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

/**
 * @ClassName: SetActivity
 * @Desciption: //设置界面
 * @author: zhangshihao
 * @date: 2018-09-21
 */
public class SetActivity extends NavigationLoseActivity implements View.OnClickListener, VerificationCodeView.OnCodeFinishListener {

    private static final String TAG = SetActivity.class.getSimpleName();

    private Button btnLogout;
    private TextView tvCurrentVersion;
    private Button btnCheckUpdate;
    private Button clearCacheButton;

    private VerificationCodeView veriCodeView;
    private Dialog parentPswDialog;
    private FingerprintIdentify mFingerprintIdentify;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);

        setTitle("设置");

        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(parentPswDialog != null){
            parentPswDialog.dismiss();
        }

        if(mFingerprintIdentify != null){
            mFingerprintIdentify.cancelIdentify();
        }
    }

    private void initView(){
        btnLogout = findViewById(R.id.btn_logout);
        btnLogout.setOnClickListener(this);
        tvCurrentVersion = findViewById(R.id.tv_current_version);
        tvCurrentVersion.setText("当前版本 "+DeviceUtil.getVersionName(this));
        btnCheckUpdate = findViewById(R.id.btn_check_update);
        btnCheckUpdate.setOnClickListener(this);
        clearCacheButton = findViewById(R.id.clear_cache_btn);
        clearCacheButton.setOnClickListener(this);
        if(getPackageName().equals(Constants.HUAWEI_PACKAGE_NAME)){
            btnCheckUpdate.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_logout://退出登陆
                logout();
                break;
            case R.id.btn_check_update://检查更新
                getUpdate();
                break;
            case R.id.clear_cache_btn:
                showDelDialog();
                break;
            default:
                break;
        }
    }

    private void getUpdate() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.APP_VERSION);
        urlParse.putValue("system",Constants.OS_TYPE)
                .putValue("version", DeviceUtil.getVersionName(this));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UpdateBean>() {

                    @Override
                    protected void onSuccess(UpdateBean userBean) {
                        if(userBean != null){
                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(
                                    Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);

                            if(isChildControl){
                                showPswUpdateDialog(userBean);
                            }else {
                                showUpdateDialog(userBean);
                            }

                        }else{
                            showToast("返回数据为空");
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }

                });
    }

    private void showUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_no_psw_dialog);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);


        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });

        Button btnUpdate = updateDialog.findViewById(R.id.update_dialog_update_btn);
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();

                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(SetActivity.this)//设置上下文
                        .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                        .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                        .setNotificationIconRes(R.drawable.logo)//设置通知图标
                        .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                        .setNotificationTitle("书山宝")//设置通知标题
                        .startDownLoad();//开始下载
            }
        });

        updateDialog.show();
    }

    private void showPswUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_dialog);
        updateDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);

        final VerificationCodeView veriCodeView = updateDialog.findViewById(R.id.update_dialog_verification_code_view);
        veriCodeView.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onComplete(String content) {

                if(StringTools.pswValide(content)){
                    updateDialog.dismiss();

                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(SetActivity.this)//设置上下文
                            .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                            .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                            .setNotificationIconRes(R.drawable.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                            .setNotificationTitle("书山宝")//设置通知标题
                            .startDownLoad();//开始下载
                }else{
                    showToast("家长密码错误");
                    veriCodeView.clear();
                }
            }
        });

        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                if(mFingerprintIdentify != null){
                    mFingerprintIdentify.cancelIdentify();
                }
            }
        });

        if(mFingerprintIdentify == null){
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG,exception.getLocalizedMessage());
                }
            });
        }

        ImageView fingerIconImg = updateDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = updateDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if(mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()){

            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView)updateDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码进行下载");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    updateDialog.dismiss();

                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(SetActivity.this)//设置上下文
                            .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                            .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                            .setNotificationIconRes(R.drawable.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                            .setNotificationTitle("书山宝")//设置通知标题
                            .startDownLoad();//开始下载
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(SetActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(SetActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(SetActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        }else {
            fingerIconImg.setVisibility(View.GONE);
            ((TextView)updateDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码进行下载");
        }

        updateDialog.show();
    }

    private void showLogoutDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("您是否确认退出登录？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        doLogout();
                    }
                })
                .create().show();
    }

    private void showParentPswDialog() {
        if(parentPswDialog == null){
            parentPswDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            parentPswDialog.setContentView(R.layout.change_to_parent_dialog);
            parentPswDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

            veriCodeView = parentPswDialog.findViewById(R.id.verification_code_view);
            veriCodeView.setOnCodeFinishListener(this);
            Button coloseButton = parentPswDialog.findViewById(R.id.btn_cancel);
            coloseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    parentPswDialog.dismiss();
                    if(mFingerprintIdentify != null){
                        mFingerprintIdentify.cancelIdentify();
                    }
                }
            });

            parentPswDialog.setCancelable(false);
        }

        if(mFingerprintIdentify == null){
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG,exception.getLocalizedMessage());
                }
            });
        }

        ImageView parentImg = parentPswDialog.findViewById(R.id.parent_psw_img);
        ImageView fingerIconImg = parentPswDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = parentPswDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if(mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()){

            parentImg.setVisibility(View.GONE);
            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView)parentPswDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码退出登录");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    doLogout();
                    parentPswDialog.dismiss();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(SetActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);

                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(SetActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(SetActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        }else {
            parentImg.setVisibility(View.VISIBLE);
            fingerIconImg.setVisibility(View.GONE);
            ((TextView)parentPswDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码退出登录");
        }

        if(veriCodeView != null){
            veriCodeView.clear();
        }

        if(!parentPswDialog.isShowing()){
            parentPswDialog.show();
        }
    }

    private void logout() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl || TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
            showLogoutDialog();
            return;
        }

        showParentPswDialog();
    }

    private void doLogout(){
        final PushAgent mPushAgent = PushAgent.getInstance(this);
        int currentChildId = shuShanApplication.getCurrentChildId();
        if(currentChildId > 0){
            mPushAgent.deleteAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
        if(useId > 0){
            mPushAgent.deleteAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        UmengEventUtil.onProfileSignOff();

        Intent intent = new Intent(this,LoginOrRegisterActivity.class);
        intent.putExtra("isLogout",true);
        startActivityAllow(intent);

        onBackAction();
        SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            doLogout();
        }else {
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }
        }
    }

    private void showDelDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("检测到" + FileSizeUtil.getAutoFileOrFilesSize(Constants.DOWNLOAD_FOLDER) + "缓存，删除将会导致重新下载，是否删除？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("清除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        ToolUtils.deleteFile(Constants.DOWNLOAD_FOLDER);
                        showToast("清除成功");
                    }
                })
                .create().show();
    }
}
